package com.acme.domain.client;

import java.io.Serializable;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

import com.acme.domain.account.Account;

public class Client implements Serializable {

	private static final long serialVersionUID = 1L;
	private String name;
	private Gender gender;

	private Set<Account> accounts = new TreeSet<Account>();

	public Client(final String name, final Gender gender) {
		this.name = name;
		this.gender = gender;
	}

	public String getName() {
		return name;
	}

	public String getSalutation() {
		if (gender != null) {
			return gender.getSalutation() + " " + name;
		} else {
			return name;
		}
	}

	public Account getAccount(final int id) {
		for (Account acc:accounts){
			if(acc.getAccountNumber() == id){
				return acc;
			}
		}
		return null;
	}

	public void addAccount(final Account account) {
		accounts.add(account);
	}

	@Override
	public String toString() {
		StringBuffer accs = new StringBuffer(getSalutation() + " accounts:");
		for (Account clientAcc : accounts) {
			accs.append(clientAcc.toString());
		}
		return accs.toString();
	}

	public Set<Account> getAccountsList() {
		return Collections.unmodifiableSet(accounts);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		if (accounts == null){
			result = prime * result;
		} else {
			result = prime * result + accounts.hashCode();
		}
		if (gender == null){
			result = prime * result;
		} else {
			result = prime * result + gender.hashCode();
		}
		if (name == null){
			result = prime * result;
		} else {
			result = prime * result + name.hashCode();
		}
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Client)) {
			return false;
		}
		Client other = (Client) obj;
		if (accounts == null) {
			if (other.accounts != null) {
				return false;
			}
		} else if (!accounts.equals(other.accounts)) {
			return false;
		}
		if (gender != other.gender) {
			return false;
		}
		if (name == null) {
			if (other.name != null) {
				return false;
			}
		} else if (!name.equals(other.name)) {
			return false;
		}
		return true;
	}


}
